import { ReactNativeBlobUtilConfig } from 'react-native-blob-util';
import ReactNativeBlobUtil from 'react-native-blob-util';
import Toast from 'react-native-toast-message';

import { CameraRoll } from '@react-native-camera-roll/camera-roll';
import { SaveToCameraRollOptions } from '@react-native-camera-roll/camera-roll/src/CameraRoll.ts';

// 下载文件到本机，例如下载图片
export const downloadFile = {
  /**
   * 下载多媒体文件到本地
   * @param imageUrl
   * @param fileName
   * @param type, video or photo(default)
   */
  async downloadMediaFile(
    imageUrl: string,
    fileName: string = 'image.png',
    type: SaveToCameraRollOptions['type'] = 'photo',
  ): Promise<void> {
    if (!imageUrl) {
      return;
    }
    try {
      // 提示正在下载中
      Toast.show({
        type: 'lightWeightToast',
        props: {
          _subType: 'loading',
          _message: 'Downloading...',
        },
      });
      const { config, fs } = ReactNativeBlobUtil;
      // ios下载路径
      const saveDir = fs.dirs.DocumentDir;

      const downloadTask = config({
        path: saveDir + '/' + fileName,
      }).fetch('GET', imageUrl);

      await downloadTask.then((data) => {
        CameraRoll.saveAsset(data.path(), { type: type })
          .then(() => {
            Toast.show({
              type: 'lightWeightToast',
              props: {
                _subType: 'success',
                _message: 'Save successful',
              },
            });
          })
          .catch((err) => {
            console.error('Error saving===', err);
            Toast.show({
              type: 'lightWeightToast',
              props: {
                _message: 'Save failed',
              },
            });
          });
      });
    } catch (e) {
      console.error(e);
      Toast.show({
        type: 'lightWeightToast',
        props: {
          _message: 'Save failed',
        },
      });
    }
  },
  /**
   * 下载多媒体文件到本地
   * @param uri
   * @param fileName
   * @param type, video or photo(default)
   */
  downloadVideo(uri: string, options?: ReactNativeBlobUtilConfig) {
    if (!uri) {
      return;
    }
    try {
      const { config, fs } = ReactNativeBlobUtil;
      const saveDir = fs.dirs.CacheDir;
      const fileName = uri.split('/').pop() || 'video.mp4';
      const downloadTask = config({
        path: saveDir + '/' + fileName,
        ...options,
      }).fetch('GET', uri);

      return downloadTask.progress((current, total) => {
        console.log(`Download progress:${fileName} | ${(+current / +total) * 100}% | ${current}/${total}`);
      });
    } catch (e) {
      console.error('我报错了 =', e);
    }
  },
  /** 下载文件,并返回文件路径 */
  async downloadFile(url: string, options?: ReactNativeBlobUtilConfig): Promise<string> {
    const { config, fs } = ReactNativeBlobUtil;
    // 缓存路径
    const saveDir = fs.dirs.CacheDir;
    const fileName = url.split('/').pop() || '';
    const downloadTask = config({
      path: saveDir + '/' + fileName,
      ...options,
    }).fetch('GET', url);
    return await downloadTask.then((data) => data.path());
  },
};
